<?php
namespace logic\sys\power;
/**
 * 角色的权限管理
 */
class RoleMenu{
    
    private $User;
    public function __construct(\logic\user\User $user){
        $this->User = $user;
    }
    
    /**
     * 读取角色的权限列表
     */
    public function getRolePowerList($roleid){
        
        $list = D("RoleMenu",'sysPower')->getPowerList($roleid);
        return $list;
        
    }    
    
    /**
     * 获取角色的权限节点
     */
    public function getList($roleid){
        $list = D("RoleMenu",'sysPower')->getList(['roleid'=>$roleid,'status'=>1]);
        return array_key_column($list,'menuid');
    }
    
    /**
     * 编辑角色的权限
     */
    public function editPower($roleid,array $menuidList){
        $menuidList = array_filter( array_unique($menuidList));
        
        $oldList =  D("RoleMenu",'sysPower')->getList(['roleid'=>$roleid]);
        foreach( $oldList as $key => $val ) $noldist[$val['status']][] = $val;
        
        $oldList = $noldist[1] ? array_key_column($noldist[1],'menuid') : [];
        $oldListClose = $noldist[2] ? array_key_column($noldist[2],'menuid') : [];
        
        $addList = array_diff($menuidList,$oldList);
        $delList = array_diff($oldList,$menuidList);
        $openList= array_intersect($menuidList,$oldListClose);
        
        $model =  M();
        try{
            $model->startTrans();
            if( $addList ){
                D("RoleMenu",'sysPower')->add($roleid,$addList);
            }
            if( $delList ){
                D("RoleMenu",'sysPower')->editStatus($roleid,$delList,2);
            }
            if( $openList ){
                D("RoleMenu",'sysPower')->editStatus($roleid,$openList,1);
            }
            $model->commit();
            return true;
        }catch(\think\Exception $e){
            $model->rollBack();
            logicE($e->getMessage());
        }
    }
    
}

